package com.xingchi.tornado.dict.service;

import com.xingchi.tornado.dict.enums.DictStorageTypeEnum;
import com.xingchi.tornado.dict.model.DictMetadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xingchi.tornado.dict.constants.DictConstants.DICT_REDIS_STORAGE_KEY;

/**
 * redis存储
 *
 * @author xingchi
 * @date 2024/5/19 20:40
 */
@Slf4j
public class RedisDictStorageService implements DictStorageService, InitializingBean {

    private final RedisTemplate<String, List<DictMetadata.Item>> redisTemplate;

    public RedisDictStorageService(RedisTemplate<String, List<DictMetadata.Item>> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private BoundHashOperations<String, String, List<DictMetadata.Item>> operations;

    /**
     * 存储字典数据
     *
     * @param dictMetadataList 字典数据集合
     */
    @Override
    public void storage(List<DictMetadata> dictMetadataList) {

        for (DictMetadata dictMetadata : dictMetadataList) {
            String group = dictMetadata.getGroup();
            List<DictMetadata.Item> items = dictMetadata.getItems();
            operations.put(group, items);
        }
    }

    /**
     * 获取所有字典项
     *
     * @return 所有字典项
     */
    @Override
    public Map<String, List<DictMetadata.Item>> getAllDictItems() {
        return operations.entries();
    }

    /**
     * 根据字典分组获取字典数据
     *
     * @param group 分组项
     * @return 字典数据
     */
    @Override
    public List<DictMetadata.Item> getDictItems(String group) {
        return operations.get(group);
    }

    /**
     * 存储类型
     *
     * @param storageType 存储类型
     * @return 是否支持
     */
    @Override
    public boolean supports(Integer storageType) {
        return DictStorageTypeEnum.REDIS.isType(storageType);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        operations = redisTemplate.boundHashOps(DICT_REDIS_STORAGE_KEY);
    }
}
